package ru.hh.team02.chat.clientcomputer;

import ru.hh.team02.chat.utils.StringSocket;

import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

public class ClientWriter implements Runnable {
    private static final int LOCAL_PORT = 5555;

    private int localPort;
    private StringSocket socket;

    public static void main(String[] args) {
        int localPort;
        if (args.length == 0) {
            localPort = LOCAL_PORT;
        } else {
            localPort = Integer.parseInt(args[0]);
        }
        new ClientWriter(localPort).run();
    }

    public ClientWriter(int localPort) {
        this.localPort = localPort;
    }

    @Override
    public void run() {
        Scanner scanner = new Scanner(System.in);
        try {
            socket = new StringSocket(new Socket("localhost", localPort));
            System.out.println("You may type command into here.");
            String input = "";
            do {
                input = scanner.nextLine();
                socket.write(input);
            } while (!input.equals("exit"));
        } catch (IOException e) {
            System.out.println("Can't connect to client reader. Terminating.");
            return;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            scanner.close();
            if (socket != null) {
                socket.close();
            }
        }
    }
}
